import React, {FC, useContext, useEffect, useRef} from 'react';
import {Button, Divider, Flex, Form, Input, InputRef, message, Typography} from "antd";
import {CommonRegex, KfInput, KfQuickForm} from "kf-web-library";
import {useRequest} from "ahooks";
import * as API from "@/services";
import lodash from "lodash";
import {SendVerificationCode} from "@/services";
import {FormattedMessage, useIntl, useModel} from "@@/exports";
import KfCountdownButton from "@kf-web-library/components/es/KfCountdownButton/KfCountdownButton";
import {HxConfigContext} from "@/layouts/HxConfigContext";

interface EmailModifyFormProps {
}

const EmailModifyForm: FC<EmailModifyFormProps> = (props) => {
  const {initialState} = useModel('@@initialState');
  const userInfo = initialState?.currentUserInfo;
  const {isZhCN} = useContext(HxConfigContext)
  const [form] = Form.useForm();
  const intl= useIntl();
  const oldVCodeInputRef = useRef<InputRef>(null);
  const newVCodeInputRef = useRef<InputRef>(null);

  const sendVerificationCodeReq = useRequest((
    p: SendVerificationCode,
    fillFieldName: string,
    inputRef?: React.RefObject<InputRef>) => {
    return API.sendVerificationCode(p)
  }, {
    manual: true,
    onError: (e: any, p) => {
      if (e?.response?.data?.bizcode == 409011) {
        p[2]?.current?.focus?.();
      }
    },
    onSuccess: (resp, p) => {
      if (resp.flag) {
        if (lodash.isString(resp.data)) {
          //测试环境, 验证码会直接返回出来, 这里回填回去
          form.setFieldValue(p[1], resp.data)
        }
        message.success(<>已发送至<Typography.Text type="success">{p[0].emailOrMobile}</Typography.Text>，请注意接收</>);
      }
    }
  })

  useEffect(() => {
    form.setFieldValue("oldEmailOrMobile", userInfo?.email)
  }, [userInfo]);


  return (
    <KfQuickForm
      formType={"emailModify"}
      submitButtonText={<FormattedMessage id="text.submit"/>}
      formProps={{
        form,
        className: "email-modify-form",
        labelCol: {
          flex: isZhCN ?'0 0 120px': '0 0 180px'
        },
        wrapperCol: {
          flex: "1"
        },
      }}
      submitRequest={{
        emailModify: (formValues) => {
          return API.changeEmail({...formValues})
        }
      }}
    >
      {
        userInfo?.email && (
          <>
            <Form.Item
              label={<FormattedMessage id="text.current-mobile"/>}
              name="oldEmailOrMobile"
              rules={[{required: true}]}
            >
              <KfInput size={"large"} readonly={true}/>
            </Form.Item>
            <Form.Item
              label={<FormattedMessage id="text.email-verification-code"/>}
              required
            >
              <Flex vertical={false} gap={6}>
                <Form.Item
                  name="oldVerificationCode"
                  help=""
                  noStyle
                  hasFeedback={true}
                  rules={[{required: true, message: `请输入收到的邮件验证码`}]}
                >
                  <Input ref={oldVCodeInputRef} maxLength={6} size={"large"} placeholder={`请输入收到的邮件验证码`}/>
                </Form.Item>

                <KfCountdownButton
                  color="primary"
                  variant="filled"
                  size={"large"}
                  style={{width: 160, fontSize: 16}}
                  onClick={() => {
                    const oldMobile = form.getFieldValue("oldEmailOrMobile");
                    if (!oldMobile) {
                      message.error("请先输入邮箱号");
                      return;
                    }
                    return new Promise((resolve, reject) => {
                      sendVerificationCodeReq.runAsync(
                        {
                          emailOrMobile: oldMobile,
                          verificationCodeType: "OLD_VERIFICATION_CODE_EMAIL",
                        },
                        "oldVerificationCode",
                        oldVCodeInputRef
                      ).then(resp => {
                        return resp.flag ? resolve() : reject()
                      }).catch((error) => {
                        reject();
                        form.setFieldValue("oldVerificationCode","")
                        oldVCodeInputRef.current?.focus?.();
                      })
                    })
                  }}
                >
                  <FormattedMessage id="text.send-verification-code"/>
                </KfCountdownButton>
              </Flex>
            </Form.Item>
            <Divider />
          </>
        )
      }


      <Form.Item
        label={<FormattedMessage id="text.new-email"/>}
        name="emailOrMobile"
        rules={[
          {required: true},
          {
            pattern: CommonRegex.EMAIL_NUMBER_REGEX,
            message: '请输入正确的邮箱格式',
          }
        ]}
        style={{marginTop: 32}}
      >
        <KfInput size={"large"}/>
      </Form.Item>
      <Form.Item
        label={ <FormattedMessage id="text.email-verification-code"/>}
        required
      >
        <Flex vertical={false} gap={6}>
          <Form.Item
            name="newVerificationCode"
            help=""
            noStyle
            hasFeedback={true}
            rules={[{required: true, message: `请输入收到的邮件验证码`}]}
          >
            <Input ref={newVCodeInputRef} size={"large"} placeholder={`请输入收到的邮件验证码`}/>
          </Form.Item>

          <KfCountdownButton
            color="primary"
            variant="filled"
            size={"large"}
            style={{width: 160, fontSize: 16}}
            onClick={() => {
              const newEmail = form.getFieldValue("emailOrMobile");
              if (!newEmail) {
                message.error("请先输入邮箱");
                return;
              }
              return new Promise((resolve, reject) => {
                sendVerificationCodeReq.runAsync({
                  emailOrMobile: newEmail,
                  verificationCodeType: "NEW_VERIFICATION_CODE_EMAIL",
                }, "newVerificationCode", newVCodeInputRef).then(resp => {
                  return resp.flag ? resolve() : reject()
                }).catch((error) => {
                  reject()
                  form.setFieldValue("newVerificationCode","")
                  newVCodeInputRef.current?.focus?.();
                });
              });
            }}
          >
            <FormattedMessage id="text.send-verification-code"/>
          </KfCountdownButton>
        </Flex>
      </Form.Item>
    </KfQuickForm>
  );
};

export default EmailModifyForm;
